package Tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 22.完全二叉树的节点个数  11.28
 * 给你一棵 完全二叉树 的根节点 root ，求出该树的节点个数。
 * 完全二叉树 的定义如下：在完全二叉树中，除了最底层节点可能没填满外，其余每层节点数都达到最大值，并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层，则该层包含 1~ 2h 个节点。
 */
public class countNodes {
    /**
     * 一刷
     * 层序遍历
     */
    public int countNodes(TreeNode root) {
        if (root == null)
            return 0;

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        int count = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                count++;
            }
        }
        return count;
    }

    /**
     * 二刷
     */
    public static int countNodes2(TreeNode root) {
        if (root == null) return 0;
        if(isBalanced(root)) return (int) (Math.pow(2,getheight(root))-1);
        return countNodes2(root.left) + countNodes2(root.right)+1;
    }

    public static boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        int height = getheight(root);
        for (int i = 1; i < height; i++) {
            if (root.right != null) {
                root = root.right;
            } else {
                return false;
            }
        }
        return  true;
    }

    public static int getheight(TreeNode root) {
        if (root == null) return 0;
        int left = getheight(root.left);
        int right = getheight(root.right);
        return Math.max(left, right) + 1;
    }
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        System.out.println(countNodes2(root));
    }
}
